package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.android.uu.utils.PriceTextChangedListener;
import com.android.uu.utils.uuUtils;
import com.android.uu.view.ActionSheetDialog;
import com.android.uu.view.ActionSheetDialog.OnSheetItemClickListener;
import com.android.uu.view.ActionSheetDialog.SheetItemColor;
import com.hemaapp.BaseConfig;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.AddImageAdapter;
import com.hemaapp.yjnh.bean.BlogDetail;
import com.hemaapp.yjnh.bean.BlogType;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.Img;
import com.hemaapp.yjnh.bean.ImgItemsBean;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.view.ImageGridView;
import com.hemaapp.yjnh.view.WheelSelectorDialog;
import com.hemaapp.yjnh.view.YjnhImageWay;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import xtom.frame.util.XtomFileUtil;
import xtom.frame.util.XtomImageUtil;
import xtom.frame.util.XtomToastUtil;

/**
 * 类描述：发布田家农货
 * 创建人：GuiyouZhang
 * 创建时间：2016/11/1
 * 修改备注：
 */
public class ReleaseGoodsActivity extends BaseActivity implements OnClickListener {

    private final static int REQUEST_CAMERA = 0x01;
    private final static int REQUEST_ALBUM = 0x02;
    @Bind(R.id.title_left_btn)
    ImageButton titleLeftBtn;
    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.image_grid)
    ImageGridView imageGrid;
    @Bind(R.id.tv_on_shelf)
    TextView tvOnShelf;
    @Bind(R.id.tv_off_shelf)
    TextView tvOffShelf;
    @Bind(R.id.tv_return_ok)
    TextView tvReturnOk;
    @Bind(R.id.tv_return_off)
    TextView tvReturnOff;
    @Bind(R.id.edt_name)
    EditText edtName;
    @Bind(R.id.tv_type)
    TextView tvType;
    @Bind(R.id.edt_price)
    EditText edtPrice;
    @Bind(R.id.edt_score)
    EditText edtScore;
    @Bind(R.id.edt_price_old)
    EditText edtPriceOld;
    @Bind(R.id.edt_freight)
    EditText edtFreight;
    @Bind(R.id.edt_spec)
    EditText edtSpec;
//    @Bind(R.id.edt_weight)
//    EditText edtWeight;
    @Bind(R.id.edt_leftcount)
    EditText edtLeftCount;
    @Bind(R.id.edt_content)
    EditText edtContent;
    @Bind(R.id.image_detail_grid)
    ImageGridView imageDetailGrid;

    private BlogDetail blog;//商品详情
    private String saleflag = "1";//农货售卖状态	0：关闭；1：进行中
    private String returnflag = "1";//,0不支持；1支持
    private String blog_id = "无";//商品id
    private User user;
    private ArrayList<String> types = new ArrayList<>();
    private YjnhImageWay imageWay;
    private int curImage;//在拍照和调用相册时使用：0轮播图片，1商品详情图片,2以及以后为附加费用图片
    private AddImageAdapter autoAdapter;
    private AddImageAdapter detailAdapter;
    private ArrayList<ImgItemsBean> delImages = new ArrayList<>();//待删除的网络图片
    private ArrayList<ImgItemsBean> autoImg = new ArrayList<>();//轮播图片
    private ArrayList<ImgItemsBean> detailsImg = new ArrayList<>();//详情图片
    private ArrayList<String> compressPaths;//压缩图片的路径，用于最后删除
    private int[] imgOrders = new int[3];//上传图片的排序,依次是轮播图、商品详情图、附加费用图

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_release_goods);
        ButterKnife.bind(this);
        user = getApplicationContext().getUser();
        super.onCreate(savedInstanceState);
        imageWay = new YjnhImageWay(mContext, REQUEST_ALBUM, REQUEST_CAMERA) {
            @Override
            public void album() {
                // 注意：若不重写该方法则使用系统相册选取(对应的onActivityResult中的处理方法也应不同)
                Intent it = new Intent(mContext, AlbumActivity.class);
                int size = 4;
                if (curImage == 0)
                    size = autoImg.size();
                else if (curImage == 1)
                    size = detailsImg.size();
                else if (curImage >= 2) {
//                    size = additionImages.get(curImage-2).size();
                }
                it.putExtra("limitCount", 4 - size);// 图片选择张数限制
                it.putExtra("model", 1);// 图片是单选还是多选
                startActivityForResult(it, albumRequestCode);
            }
        };
        if (!blog_id.equals("无")) {
            getNetWorker().getBlogDetail(user.getToken(), blog_id);
        }else {
            refreshADImages();
            refreshDetailImages();
        }
        getNetWorker().getBlogTypeList("4", "0");
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void getExras() {
        blog_id = mIntent.getStringExtra("blog_id");
        if (isNull(blog_id)) {
            blog_id = "无";
        }
    }

    @Override
    protected void setListener() {
        if (blog_id.equals("无"))
            titleText.setText("发布商品");
        else
            titleText.setText("编辑商品");
        titleRightBtn.setText("确定");
        edtPrice.addTextChangedListener(new PriceTextChangedListener(2, edtPrice));
        edtScore.addTextChangedListener(new PriceTextChangedListener(2, edtScore));
        edtPriceOld.addTextChangedListener(new PriceTextChangedListener(2, edtPriceOld));
        edtFreight.addTextChangedListener(new PriceTextChangedListener(2, edtFreight));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (compressPaths != null)
            for (String path : compressPaths) {
                File file = new File(path);
                file.delete();
            }
    }

    /**
     * 如果是修改已经发布过的商品
     * 那么将商品信息显示到编辑框中
     */
    private void setData() {
        if (blog.getSaleflag().equals("1")) {//1上架；0下架
            tvOnShelf.setTextColor(getResources().getColor(R.color.text_orange));
            tvOffShelf.setTextColor(getResources().getColor(R.color.text_grey));
            saleflag = "1";
        } else if (blog.getSaleflag().equals("0")) {
            tvOnShelf.setTextColor(getResources().getColor(R.color.text_grey));
            tvOffShelf.setTextColor(getResources().getColor(R.color.text_orange));
            saleflag = "0";
        }
        if (blog.getReturnflag().equals("1")) {//1能退；0不能
            tvReturnOk.setTextColor(getResources().getColor(R.color.text_orange));
            tvReturnOff.setTextColor(getResources().getColor(R.color.text_grey));
            returnflag = "1";
        } else if (blog.getReturnflag().equals("0")) {
            tvReturnOk.setTextColor(getResources().getColor(R.color.text_grey));
            tvReturnOff.setTextColor(getResources().getColor(R.color.text_orange));
            returnflag = "0";
        }
        edtName.setText(blog.getName());
        tvType.setText(blog.getTypename());
        edtPrice.setText(uuUtils.formatAfterDot2(blog.getPrice()));
        edtScore.setText(uuUtils.formatAfterDot2(blog.getScore()));
        edtPriceOld.setText(uuUtils.formatAfterDot2(blog.getOldprice()));
        edtFreight.setText(uuUtils.formatAfterDot2(blog.getExpressfee()));
        edtSpec.setText(blog.getUnit());
        edtContent.setText(blog.getContent());
        edtLeftCount.setText(blog.getLeftcount());
        autoImg.clear();
        autoImg.addAll(blog.getImgItems());
        detailsImg.clear();
        detailsImg.addAll(blog.getImg2Items());
        refreshADImages();
        refreshDetailImages();
        try {
            int max = 0;
            for (ImgItemsBean item : autoImg) {
                int orderby = Integer.parseInt(item.getOrderby());
                max = orderby > max ? orderby:max;
            }
            imgOrders[0] = max+1;
            max = 0;
            for (ImgItemsBean item : detailsImg) {
                int orderby = Integer.parseInt(item.getOrderby());
                max = orderby > max ? orderby:max;
            }
            imgOrders[1] = max+1;
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_GET:
            case FILE_UPLOAD:
            case BLOGTYPE_LIST:
            case BLOG_ADD:
            case IMG_DELOPERATE:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_GET:
            case FILE_UPLOAD:
            case BLOGTYPE_LIST:
            case IMG_DELOPERATE:
            case BLOG_ADD:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_GET:
                HemaArrayResult<BlogDetail> bResult = (HemaArrayResult<BlogDetail>) baseResult;
                blog = bResult.getObjects().get(0);
                if (blog == null) {
                    showTextDialog("获取商品信息失败！");
                    titleText.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            finish();
                        }
                    }, 1000);
                } else {
                    setData();
                }
                break;
            case BLOGTYPE_LIST:
                HemaArrayResult<BlogType> typeResult = (HemaArrayResult<BlogType>) baseResult;
                if (typeResult == null || typeResult.getObjects() == null)
                    return;
                String keytype1 = netTask.getParams().get("keytype");
                if (keytype1.equals("4")) {
                    ArrayList<BlogType> types = new ArrayList<>();
                    types.clear();
                    types.addAll(typeResult.getObjects());
                    for (BlogType type : types) {
                        this.types.add(type.getName());
                    }
                }
                break;
            case BLOG_ADD:
                HemaArrayResult<String> sResult = (HemaArrayResult<String>) baseResult;
                blog_id = sResult.getObjects().get(0);
                if (blog != null) {
                    blog_id = blog.getId();
                } else {
                    blog_id = sResult.getObjects().get(0);
                }
                //删掉要删除的图片
                if (delImages.size() > 0) {
                    delNetImage();
                } else {
                    upAutoImages();
                }
                break;
            case IMG_DELOPERATE:
                delImages.remove(0);
                if (delImages.size() > 0) {
                    delNetImage();
                } else {
                    upAutoImages();
                }
                break;
            case FILE_UPLOAD:
                String keytype = netTask.getParams().get("keytype");
                if (keytype.equals("2")) {//上传完一张轮播图，开始上传下一张轮播图
                    autoImg.remove(0);
                    upAutoImages();
                } else if (keytype.equals("19")) {//上传完一张详情图，开始上传下一张详情图
                    detailsImg.remove(0);
                    upDetailImages();
                }
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_ADD:
                XtomToastUtil.showShortToast(mContext, "发布失败，" + baseResult.getMsg());
                break;
            case FILE_UPLOAD:
                XtomToastUtil.showShortToast(mContext, "图片上传失败，" + baseResult.getMsg());
                break;
            case BLOG_GET:
                XtomToastUtil.showShortToast(mContext, "获取商品信息失败，" + baseResult.getMsg());
                break;
            case IMG_DELOPERATE:
                XtomToastUtil.showShortToast(mContext, "图片删除失败，" + baseResult.getMsg());
                break;
            case BLOGTYPE_LIST:
                XtomToastUtil.showShortToast(mContext, "获取商品分类失败，" + baseResult.getMsg());
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_ADD:
                XtomToastUtil.showShortToast(mContext, "发布失败，请稍候再试");
                break;
            case FILE_UPLOAD:
                XtomToastUtil.showShortToast(mContext, "图片上传失败，请稍候再试");
                break;
            case BLOG_GET:
                XtomToastUtil.showShortToast(mContext, "获取商品信息失败，请稍候再试");
                break;
            case IMG_DELOPERATE:
                XtomToastUtil.showShortToast(mContext, "图片删除失败，请稍候再试");
                break;
            case BLOGTYPE_LIST:
                XtomToastUtil.showShortToast(mContext, "获取商品分类失败，请稍候再试");
                break;
        }
    }

    private void delNetImage() {
        ImgItemsBean item = delImages.get(0);
        getNetWorker().imgDel(user.getToken(), item.getId());
    }

    /**
     * 上传轮播图
     */
    private void upAutoImages() {
        if (autoImg.size() > 0) {
            String imagePath = autoImg.get(0).getImgurl();
            if (!imagePath.startsWith("http")) {//只上传新的图片
                getNetWorker().fileUpload(user.getToken(), "2", blog_id,
                        "0", imgOrders[0] + "", "无", imagePath);
                imgOrders[0]++;
            } else {
                autoImg.remove(0);
                upAutoImages();
            }
        } else {
            upDetailImages();
        }
    }

    /**
     * 上传详细介绍
     */
    private void upDetailImages() {
        if (detailsImg.size() > 0) {
            String imagePath = detailsImg.get(0).getImgurl();
            if (!imagePath.startsWith("http")) {//只上传新的图片
                getNetWorker().fileUpload(user.getToken(), "19", blog_id,
                        "0", imgOrders[1] + "", "无", imagePath);
                imgOrders[1]++;
            } else {
                detailsImg.remove(0);
                upDetailImages();
            }
        } else {
            showTextDialog("发布成功!");
            EventBusMsg msg = new EventBusMsg();
            msg.setType(EventBusConfig.NEW_GOODS);
            EventBus.getDefault().post(msg);
            titleText.postDelayed(new Runnable() {

                @Override
                public void run() {
                    setResult(RESULT_OK);
                    finish();
                }
            }, 1500);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (RESULT_OK != resultCode) {
            return;
        }
        switch (requestCode) {
            case REQUEST_ALBUM:// 相册选择图片
                album(data);
//                albumSys(data);
                break;
            case REQUEST_CAMERA:// 拍照
                camera();
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @OnClick({R.id.tv_on_shelf, R.id.tv_off_shelf, R.id.tv_type, R.id.title_left_btn,
            R.id.title_right_btn, R.id.tv_return_ok, R.id.tv_return_off})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.title_right_btn:
                String name = edtName.getText().toString();
                String type = tvType.getText().toString();
                String price = edtPrice.getText().toString();
                String score = edtScore.getText().toString();
                String priceOld = edtPriceOld.getText().toString();
                String freight = edtFreight.getText().toString();
                String spec = edtSpec.getText().toString();
                String typename = tvType.getText().toString();
//                String weight = edtWeight.getText().toString();
                String leftcount = edtLeftCount.getText().toString();
                String content = edtContent.getText().toString();
                if (autoImg.size() == 0) {
                    XtomToastUtil.showShortToast(mContext, "商品图片不能为空");
                    return;
                }
                if (detailsImg.size() == 0) {
                    XtomToastUtil.showShortToast(mContext, "商品详细图片不能为空");
                    return;
                }
                if (isNull(name) || isNull(type) || isNull(price) || isNull(score) ||
                        isNull(priceOld) || isNull(freight) || isNull(spec) || isNull(typename) || isNull(leftcount)
                        || isNull(content)) {
                    XtomToastUtil.showShortToast(mContext, "请输入完整信息");
                    return;
                }
                try {
                    double price2 = Double.parseDouble(price);
                    double score2 = Double.parseDouble(score);
                    double priceOld2 = Double.parseDouble(priceOld);
                    if (price2 > 100000000) {
                        XtomToastUtil.showShortToast(mContext, "商品价格不能高于100,000,000元");
                        return;
                    }
                    if (priceOld2 > 100000000) {
                        XtomToastUtil.showShortToast(mContext, "商品原价不能高于100,000,000元");
                        return;
                    }
                    if (score2 > 100000000) {
                        XtomToastUtil.showShortToast(mContext, "可用粮票不能高于100,000,000元");
                        return;
                    }
                    if (score2 > price2) {
                        XtomToastUtil.showShortToast(mContext, "粮票价格不能高于商品价格");
                        return;
                    }
                    if (score2 > 100000000) {
                        XtomToastUtil.showShortToast(mContext, "可用粮票不能高于100,000,000元");
                        return;
                    }
                    if (price2 == 0 && score2 == 0) {
                        XtomToastUtil.showShortToast(mContext, "不能发布0元商品");
                        return;
                    }
                    //库存
                    int lefcount2 = Integer.parseInt(leftcount);
                    if (lefcount2 > 100000000) {
                        XtomToastUtil.showShortToast(mContext, "库存不能高于100,000,000");
                        return;
                    }
                    //运费
                    int freight2 = Integer.parseInt(freight);
                    if (freight2 > 100000000) {
                        XtomToastUtil.showShortToast(mContext, "运费不能高于100,000,000元");
                        return;
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
                getNetWorker().blogAdd(user.getToken(),
                        "1", name, price, priceOld, score, "无", spec, leftcount, freight, typename, content, blog_id, returnflag, saleflag);
                break;
            case R.id.tv_on_shelf:
                tvOnShelf.setTextColor(getResources().getColor(R.color.text_orange));
                tvOffShelf.setTextColor(getResources().getColor(R.color.text_grey));
                saleflag = "1";
                break;
            case R.id.tv_off_shelf:
                tvOnShelf.setTextColor(getResources().getColor(R.color.text_grey));
                tvOffShelf.setTextColor(getResources().getColor(R.color.text_orange));
                saleflag = "0";
                break;
            case R.id.tv_return_ok:
                tvReturnOk.setTextColor(getResources().getColor(R.color.text_orange));
                tvReturnOff.setTextColor(getResources().getColor(R.color.text_grey));
                returnflag = "1";
                break;
            case R.id.tv_return_off:
                tvReturnOk.setTextColor(getResources().getColor(R.color.text_grey));
                tvReturnOff.setTextColor(getResources().getColor(R.color.text_orange));
                returnflag = "0";
                break;
            case R.id.tv_type:
                if (types.size() == 0) {
                    XtomToastUtil.showShortToast(mContext, "暂无商品类型");
                    return;
                }
                WheelSelectorDialog wheelDialog = new WheelSelectorDialog(mContext).builder();
                wheelDialog.setListener(new WheelSelectorDialog.onSelectedItemListener() {
                    @Override
                    public void onSelected(int index) {
                        tvType.setText(types.get(index));
                    }
                });
                wheelDialog.setDatas(types);
                wheelDialog.show();
                break;
        }
    }

    /**
     * 刷新轮播图片
     */
    private void refreshADImages() {
        if (autoAdapter == null) {
            autoAdapter = new AddImageAdapter(mContext, autoImg);
            autoAdapter.setShowDelete(false);
            imageGrid.setAdapter(autoAdapter);
            autoAdapter.setImageClickListener(new AddImageAdapter.OnImageClickListener() {
                @Override
                public void onImageClickListener(int position) {
                    if (autoImg.size() < 5 && position == autoImg.size()) {
                        curImage = 0;
                        showPic();
                    }else if (position < autoImg.size()){
                        showImageOpe(position, autoImg, autoAdapter);
                    }
                }

                @Override
                public void onDeleteClickListener(int position, ImgItemsBean imageItem) {
                    if (imageItem.getImgurl().startsWith("http"))
                        delImages.add(imageItem);
                    autoImg.remove(position);
                    autoAdapter.notifyDataSetChanged();
                }
            });
        } else {
            autoAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 刷新详情图片
     */
    private void refreshDetailImages() {
        if (detailAdapter == null) {
            detailAdapter = new AddImageAdapter(mContext, detailsImg);
            detailAdapter.setShowDelete(false);
            imageDetailGrid.setAdapter(detailAdapter);
            detailAdapter.setImageClickListener(new AddImageAdapter.OnImageClickListener() {
                @Override
                public void onImageClickListener(int position) {
                    if (detailsImg.size() < 5 && position == detailsImg.size()) {
                        curImage = 1;
                        showPic();
                    }else if (position < detailsImg.size()){
                        showImageOpe(position, detailsImg, detailAdapter);
                    }
                }

                @Override
                public void onDeleteClickListener(int position, ImgItemsBean imageItem) {
                    if (imageItem.getImgurl().startsWith("http"))
                        delImages.add(imageItem);
                    detailsImg.remove(position);
                    detailAdapter.notifyDataSetChanged();
                }
            });
        } else {
            detailAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 显示图片选择对话
     */
    public void showPic() {
        new ActionSheetDialog(mContext)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("相机", SheetItemColor.Black,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                int size = 4;
                                if (curImage == 0)
                                    size = autoImg.size();
                                else if (curImage == 1)
                                    size = detailsImg.size();

                                if (size < 4) {
                                    imageWay.camera();
                                }else {
                                    XtomToastUtil.showShortToast(mContext, "最多只能添加4张图片");
                                }
                            }
                        })
                .addSheetItem("从相册打开", SheetItemColor.Black,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                int size = 4;
                                if (curImage == 0)
                                    size = autoImg.size();
                                else if (curImage == 1)
                                    size = detailsImg.size();

                                if (size < 4) {
                                    imageWay.album();
                                }else {
                                    XtomToastUtil.showShortToast(mContext, "最多只能添加4张图片");
                                }
                            }
                        })
                .show();
    }

    private void camera() {
        String imagepath = imageWay.getCameraImage();
        new CompressPicTask().execute(imagepath);
    }

    private void album(Intent data) {
        if (data == null)
            return;
        ArrayList<String> imgList = data.getStringArrayListExtra("images");
        if (imgList == null)
            return;
        for (String img : imgList) {
            new CompressPicTask().execute(img);
        }
    }

//    /**
//     * 处理系统相册
//     *
//     * @param data
//     */
//    private void albumSys(Intent data) {
//        if (data == null)
//            return;
//        String picturePath = null;
//        Uri selectedImage = data.getData();
//        String[] filePathColumn = {MediaStore.Images.Media.DATA};
//        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
//        if (cursor != null) {
//            cursor.moveToFirst();
//            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//            picturePath = cursor.getString(columnIndex);
//            cursor.close();
//            cursor = null;
//
//            if (picturePath == null || picturePath.equals("null")) {
//                Toast toast = Toast.makeText(mContext, "抱歉，没有找到图片", Toast.LENGTH_SHORT);
//                toast.setGravity(Gravity.CENTER, 0, 0);
//                toast.show();
//                return;
//            }
//        } else {
//            File file = new File(selectedImage.getPath());
//            if (!file.exists()) {
//                Toast toast = Toast.makeText(mContext, "抱歉，没有找到图片", Toast.LENGTH_SHORT);
//                toast.setGravity(Gravity.CENTER, 0, 0);
//                toast.show();
//                return;
//
//            }
//            picturePath = file.getAbsolutePath();
//        }
//        new CompressPicTask().execute(picturePath);
//    }

    /**
     * 压缩图片
     */
    private class CompressPicTask extends AsyncTask<String, Void, Integer> {
        String compressPath;

        @Override
        protected Integer doInBackground(String... params) {
            try {
                String path = params[0];
                String savedir = XtomFileUtil.getTempFileDir(mContext);
                compressPath = XtomImageUtil.compressPictureWithSaveDir(path,
                        BaseConfig.IMAGE_HEIGHT, BaseConfig.IMAGE_WIDTH,
                        BaseConfig.IMAGE_QUALITY, savedir, mContext);
                return 0;
            } catch (Exception e) {
                return 1;
            }
        }

        @Override
        protected void onPreExecute() {
            showProgressDialog("正在压缩图片");
        }

        @Override
        protected void onPostExecute(Integer result) {
            cancelProgressDialog();
            switch (result) {
                case 0:
                    if (compressPaths == null)
                        compressPaths = new ArrayList<>();
                    compressPaths.add(compressPath);
                    ImgItemsBean imageitem = new ImgItemsBean();
                    imageitem.setImgurl(compressPath);
                    if (curImage == 0) {
                        autoImg.add(imageitem);
                        refreshADImages();
                    } else if (curImage == 1) {
                        detailsImg.add(imageitem);
                        refreshDetailImages();
                    }
                    break;
                case 1:
                    showTextDialog("图片压缩失败");
                    break;
            }
        }
    }
    private void showImageOpe(final int position, final ArrayList<ImgItemsBean> images, final AddImageAdapter adapter) {
        new ActionSheetDialog(mContext)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("查看大图", SheetItemColor.Black,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                ArrayList<Img> imgs = new ArrayList<Img>();
                                for (int i = 0; i < images.size(); i++) {
                                    ImgItemsBean item = images.get(i);
                                    String imgurl_detail = item.getImgurlbig();
                                    Img img = new Img(imgurl_detail);
                                    imgs.add(img);
                                }

                                Intent intent = new Intent();
                                intent.setClass(mContext, ShowLargeImageActivity.class);
                                intent.putExtra("imgs", imgs);
                                intent.putExtra("position", position + 1);
                                mContext.startActivity(intent);
                            }
                        })
                .addSheetItem("删除", SheetItemColor.Black,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                ImgItemsBean imageItem = images.get(position);
                                if (imageItem.getImgurl().startsWith("http"))
                                    delImages.add(imageItem);
                                images.remove(position);
                                adapter.notifyDataSetChanged();
                            }
                        })
                .show();
    }
}
